package model_2_二叉树;

public class ArrayBinaryTree {
    private int[] tree;

    public ArrayBinaryTree(int[] array) {
        tree = array;
    }

    // 前序遍历
    public void preorderTraversal() {
        System.out.print("前序遍历：");
        preorderTraversal(0);
        System.out.println();
    }

    private void preorderTraversal(int index) {
        if (index < tree.length) {
            System.out.print(tree[index] + " ");
            preorderTraversal(getLeftChildIndex(index));
            preorderTraversal(getRightChildIndex(index));
        }
    }

    // 中序遍历
    public void inorderTraversal() {
        System.out.print("中序遍历：");
        inorderTraversal(0);
        System.out.println();
    }

    private void inorderTraversal(int index) {
        if (index < tree.length) {
            inorderTraversal(getLeftChildIndex(index));
            System.out.print(tree[index] + " ");
            inorderTraversal(getRightChildIndex(index));
        }
    }

    // 后序遍历
    public void postorderTraversal() {
        System.out.print("后序遍历：");
        postorderTraversal(0);
        System.out.println();
    }

    private void postorderTraversal(int index) {
        if (index < tree.length) {
            postorderTraversal(getLeftChildIndex(index));
            postorderTraversal(getRightChildIndex(index));
            System.out.print(tree[index] + " ");
        }
    }

    // 获取左子结点的索引
    private int getLeftChildIndex(int index) {
        return 2 * index + 1;
    }

    // 获取右子结点的索引
    private int getRightChildIndex(int index) {
        return 2 * index + 2;
    }

    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7};
        ArrayBinaryTree binaryTree = new ArrayBinaryTree(array);

        binaryTree.preorderTraversal();
        binaryTree.inorderTraversal();
        binaryTree.postorderTraversal();
    }
}
